package xyz.myachin.downloader.receivers

import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import xyz.myachin.downloader.*
import xyz.myachin.downloader.dm.Downloader
import xyz.myachin.downloader.settings.Settings
import xyz.myachin.downloader.ui.share.SharingType
import xyz.myachin.downloader.workmanagers.RemoveDownloadsWorker

class DownManNotifyReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {

        when (intent.action) {
            DownloadManager.ACTION_DOWNLOAD_COMPLETE -> {
                Thread {
                    if (Settings.isAutoClean()) RemoveDownloadsWorker.cleanAll(false)
                }.start()

                val taskId = downloadId(intent)

                when (Settings.getDownloadTaskIdType(taskId)) {
                    SharingType.DIRECT -> executeForDirect(taskId, context)
                    SharingType.MANUAL -> executeForManual(taskId, context)
                    SharingType.PROXY -> executeForProxy(taskId, context)
                }
            }
            DownloadManager.ACTION_NOTIFICATION_CLICKED -> {
            }
        }
    }

    private fun executeForProxy(taskId: Long, context: Context) {
        val intent = Intent(Intent.ACTION_SEND).apply {
            type = Downloader.getMimeTypeForDownloadedFile(taskId)
            putExtra(Intent.EXTRA_STREAM, Downloader.getLocalUriForDownloadedFile(taskId))
        }
        val intentChooser = Intent.createChooser(intent, "DemoText")
            .apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }
        context.startActivity(intentChooser)
    }

    private fun executeForManual(taskId: Long, context: Context) {
        executeForSaveTo(taskId, ACTION_DOWNLOADED_MANUAL_CHOOSER, context)
    }

    private fun executeForDirect(taskId: Long, context: Context) {
        executeForSaveTo(taskId, ACTION_DOWNLOADED_DIRECT_CHOOSER, context)
    }

    private fun executeForSaveTo(taskId: Long, action: String, context: Context) {
        Downloader.getLocalUriForDownloadedFile(taskId).let { uri ->
            val shareIntent = Intent(action).apply {
                putExtra(FILE_ID, taskId)
                putExtra(ORIGINAL_URL, Downloader.getRemoteUriForDownloadedFile(taskId))
                putExtra(Intent.EXTRA_STREAM, uri)

                type = Downloader.getMimeTypeForDownloadedFile(taskId)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.grantUriPermission(
                SAVE_TO_PKG,
                uri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION
            )
            context.startActivity(shareIntent)
        }
    }

    private fun downloadId(intent: Intent): Long {
        return intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
    }
}